const got = require('got')

const wsHeaders = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/132.0.0.0 Safari/537.36',
}

const dyHttpHeaders = {
    accept: '*/*',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/132.0.0.0 Safari/537.36',
    accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3',
    connection: 'keep-alive',
    Host: 'live.douyin.com',
    'sec-ch-ua': `Google Chrome;v=107, Chromium;v=107, Not=A?Brand;v=24`,
    // Referer: 'https://live.douyin.com',
    'sec-ch-ua-platform': 'macOS',
    'Sec-Fetch-Dest': 'document',
    'Sec-Fetch-Mode': 'navigate',
    'Sec-Fetch-Site': 'same-origin',
    'Sec-Fetch-User': '?1'
}

const GenerateMsToken = (length = 107) => {
    let baseStr = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789=_";
    let str = "", len = baseStr.length;
    for (let i = 0; i < length; i++) {
        str += baseStr[Math.floor(Math.random() * len)];
    }
    return str;
}

const getDouYinRoomInfo = (liveUrl) => {
    return new Promise(async (resolve, reject) => {
        const liveInfo = {
            userUniqueId: '',
            roomId: '',
            cookie: '',
			cookieObj: {ttwid: ''},
        }
        const res = await got.get(liveUrl, {
            headers: {
                Cookie: `__ac_nonce=0${GenerateMsToken(20)}; Path=/; Max-Age=1800; Secure; SameSite=None`,
                ...dyHttpHeaders
            },
        })
        //console.log('res.body', res.body)
        //console.log('setCookies', setCookies)
        const setCookies = res.headers['set-cookie']
        setCookies.forEach((c, i) => {
			liveInfo.cookie += `${i === 0 ? '' : ';'} ${c.split(';')[0]}`
			const objSplit = c.split(';')[0].split('=')
			liveInfo.cookieObj[objSplit[0]] = decodeURIComponent(objSplit[1])
		})
        //从html中 提取 的正则表达式对象 new RegExp(/ (.*?) /, 'g')
		const regs = {
			userUniqueId: new RegExp(/user_unique_id\\\":\\\"(.*?)\\\"\}/, 'g'),
            roomId: new RegExp(/owner_open_id_str(.*?)web_rid/, 'g')
		}
        //1.从html中 提取 userUniqueId
        //console.log(res.body.match(regs.userUniqueId))
        try {
            liveInfo.userUniqueId = res.body.match(regs.userUniqueId)[0].match(new RegExp(/:\\\"(.*?)\\\"/, 'g'))[0].replace(/:\\"/g, '').replace(/\\\"/g, '')
            if(!liveInfo.userUniqueId) return reject(`获取user_unique_id错误E1`);
        } catch (e) {
            return reject(`获取user_unique_id错误E2`);
        }
        //从html中 提取 roomId
        //console.log(res.body.match(regs.roomId))
        try {
            liveInfo.roomId = res.body.match(regs.roomId)[0].match(new RegExp(/Id\\\":\\\"(.*?)\\\"\,/, 'g'))[0].replace(/Id\\\":\\\"/g, '').replace(/\\\"\,/g, '')
            if(!liveInfo.roomId) return reject(`获取roomId错误E1`);
        } catch (e) {
            return reject(`获取roomId错误E2`);
        }
        resolve(liveInfo);
    });
}

module.exports = {
    wsHeaders,
    dyHttpHeaders,
    getDouYinRoomInfo
}